/* File Server
 */

package main

import (
	"fmt"
	"net/http"
	"os"
	"math/rand"
	"time"
	"encoding/json"
	"log"
	"flag"
)

var (
  bindAddress				*string = flag.String("BindAddress", ":8000", "The web server bind address") 
  fileRoot					*string = flag.String("Root", "./html", "The HTTP root address for web agent.")
)

var g_rand *rand.Rand

func main() {
  flag.Parse()
	source := rand.NewSource(time.Now().UnixNano())
	g_rand = rand.New(source)

	// deliver files from the directory
	fileServer := http.FileServer(http.Dir(*fileRoot))
	http.Handle("/", fileServer)
	
	http.HandleFunc("/login", loginHandle)
	http.HandleFunc("/logout", logoutHandle)
	http.HandleFunc("/proxy", proxyHandle)

	// register the handler and deliver requests to it
	err := http.ListenAndServe(*bindAddress, nil)
	checkError(err)
	// That's it!
}

func checkError(err error) {
	if err != nil {
		fmt.Println("Fatal error ", err.Error())
		os.Exit(1)
	}
}

type loginRequest struct {
	Uid int32
	Rid int32
	Extern_string string
}

type loginResponse struct {
	Uid int32
	Rid int32
	Exp1 int32
	Exp2 int32
	Name string
}

func loginHandle(writer http.ResponseWriter, req *http.Request) {
	fmt.Printf("login(%+v)\n", req)
	dec := json.NewDecoder(req.Body)
	var reqData loginRequest
	err := dec.Decode(&reqData)
	if err != nil {
		log.Println("Decode login request failed! error: ", err)
		return
	}
	fmt.Printf("request: %+v\n", reqData)
	resp := loginResponse{reqData.Uid, reqData.Rid, int32(g_rand.Uint32() % 10000), int32(g_rand.Uint32() % 10000), "test"}
	var respData []byte
	respData, err = json.Marshal(resp)
	if err != nil {
		log.Println("Marshal response failed! error: ", err)
		return
	}
	writer.Write(respData)
}

type logoutRequest struct {
        Uid int32
        Rid int32
}

func logoutHandle(writer http.ResponseWriter, req *http.Request) {
        fmt.Printf("logout(%+v)\n", req)

        dec := json.NewDecoder(req.Body)
        var reqData logoutRequest
        err := dec.Decode(&reqData)
        if err != nil {
                log.Println("Decode logout request failed! error: ", err)
                return
        }
        fmt.Printf("request: %+v\n", reqData)
        writer.Write(nil)
}

type cmd struct {
	Cmd string
	Value string
}

type proxyRequest struct {
        Uid int32
        Rid int32
	Msg cmd
}

func proxyHandle(writer http.ResponseWriter, req *http.Request) {
        fmt.Printf("proxy(%+v)\n", req)

        dec := json.NewDecoder(req.Body)
        var reqData proxyRequest
        err := dec.Decode(&reqData)
        if err != nil {
                log.Println("Decode proxy request failed! error: ", err)
                return
        }
        fmt.Printf("request: %+v\n", reqData)
        writer.Write(nil)
}


